package yf.mall.service.impl;

import com.github.pagehelper.PageHelper;
import yf.mall.common.Const;
import com.yf.service.impl.BaseServiceImpl;
import yf.mall.dao.*;
import yf.mall.entity.*;
import yf.mall.enums.*;
import yf.mall.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import org.springframework.transaction.annotation.Transactional;
import yf.mall.vo.ActGoodsVo;
import yf.mall.vo.PriceVo;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 产品Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Mon Aug 05 11:33:59 CST 2019
 */
@Service
public class MallGoodsServiceImpl extends BaseServiceImpl<MallGoodsEntity> implements MallGoodsService {

    private MallGoodsDao mallGoodsDao;

    @Autowired
    private MallStoreService mallStoreService;

    @Autowired
    private StockRecordDao stockRecordDao;


    @Autowired
    public void setDao(MallGoodsDao mallGoodsDao) {
        this.mallGoodsDao = mallGoodsDao;
        super.setBaseDao(mallGoodsDao);
    }


    /**
     * 内部方法
     **/

    //过滤一些字段不让前端知道
    private List<MallGoodsEntity> apiFilter(List<MallGoodsEntity> mallGoodsEntities) {
        mallGoodsEntities.forEach(mallGoodsEntity -> apiFilter(mallGoodsEntity));
        return mallGoodsEntities;
    }

    //过滤一些字段不让前端知道
    private MallGoodsEntity apiFilter(MallGoodsEntity mallGoodsEntity) {
        mallGoodsEntity.setProfit(null);
        return mallGoodsEntity;
    }


    /**
     * 外部方法实现
     **/


    @Autowired
    private MallSkuThemeDao mallSkuThemeDao;

    @Autowired
    private MallSkuItemDao mallSkuItemDao;

    @Autowired
    private MallSkuDao mallSkuDao;

    @Autowired
    private PriceService priceService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private LevelDao levelDao;

    @Autowired
    private MallActDao mallActDao;

    @Autowired
    private NoticeService noticeService;

    //更新产品并且更新Sku
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MallGoodsEntity merge(ActGoodsVo actGoodsVo, Long userId) {
        //疑似后台修改有缓存有几率采购价没有清空 导致其他模式产品会出现采购价
        if (actGoodsVo.getGoods().getSaleType() != MallGoodsSaleTypeEnum.STORES.getIndex()) {
            actGoodsVo.getGoods().setShopPrice(BigDecimal.ZERO);
        }
        saleTypeInit(actGoodsVo.getGoods().getSaleType(), actGoodsVo.getSaleTypeInfoEntity());
        if (actGoodsVo.getGoods().getId() != null) {//update
            mallGoodsDao.update(actGoodsVo.getGoods());
            //删除主题 外键会自动删除Item
            mallSkuThemeDao.deleteByGoodsId(actGoodsVo.getGoods().getId());
            //清除所有的sku
            mallSkuDao.deleteByGoodsId(actGoodsVo.getGoods().getId());
            saleTypeInfoDao.update(actGoodsVo.getSaleTypeInfoEntity());
            //修改售卖类型和资质相关信息
            updateFromGoods(actGoodsVo, userId);

            //发送通知
            if (actGoodsVo.getGoods().getShelf() != null) {
                if (userId != null) {
                    UserEntity userEntity = userDao.get(userId);
                    //下架通知
                    if (actGoodsVo.getGoods().getShelf() == MallGoodsShelfEnum.DOWN.getIndex()) {
                        noticeService.sendGoodsDown(userEntity.getMobile(), actGoodsVo.getGoods().getName());
                    }
                }
            }
        } else { //save保存
            mallGoodsDao.save(actGoodsVo.getGoods());
            //保存售卖类型和资质相关信息
            if (actGoodsVo.getGoods().getSaleType() != null && (actGoodsVo.getGoods().getSaleType() == MallGoodsSaleTypeEnum.AGENT.getIndex()||actGoodsVo.getGoods().getSaleType() == MallGoodsSaleTypeEnum.DAY_SEL.getIndex())) {
                actGoodsVo.getSaleTypeInfoEntity().setTransfer(MallActRewardTypeEnum.yes.getIndex());  //是否转货
            } else {
                actGoodsVo.getSaleTypeInfoEntity().setTransfer(MallActRewardTypeEnum.no.getIndex());  //是否转货
            }
            actGoodsVo.getSaleTypeInfoEntity().setDelivery(MallActRewardTypeEnum.yes.getIndex()); //是否发货
            initAct(actGoodsVo, actGoodsVo.getGoods());
            saleTypeInfoDao.save(actGoodsVo.getSaleTypeInfoEntity()); //保存产品关联活动
            saveFromGoods(actGoodsVo, userId);

        }
        //保存或修改活动
        saveOrUpdate(actGoodsVo);
        //更新Sku TODO 引起库存的问题 库存用增量的方式修改
        List<MallSkuThemeEntity> skuThemes = actGoodsVo.getGoods().getSkuThemes();
        if (skuThemes != null && skuThemes.size() > 0) {
            //实体化skuTheme
            mallSkuThemeDao.saveList(skuThemes, actGoodsVo.getGoods().getId());
            for (MallSkuThemeEntity skuTheme : skuThemes) {
                //实体化skuItem
                if (skuTheme.getItems().size() > 0) {
                    mallSkuItemDao.saveList(skuTheme.getItems(), skuTheme.getId());
                }
            }
        }
        List<MallSkuEntity> skuEntities = actGoodsVo.getGoods().getMallSkus();
        if (skuEntities != null && skuEntities.size() > 0) {
            mallSkuDao.saveList(actGoodsVo.getGoods().getMallSkus(), actGoodsVo.getGoods().getId());
        }
        //更新价格
        if (actGoodsVo.getGoods().getPrices() != null) {
            for (PriceEntity priceEntity : actGoodsVo.getGoods().getPrices()) {
                //更新
                if (priceEntity.getPrice() != null) {
                    if (priceEntity.getVipCode() == null) {
                        throw new RuntimeException("请填入团队编号");
                    }
                    if (priceEntity.getId() == null) {
                        priceEntity.setGoodsId(actGoodsVo.getGoods().getId());
                        priceService.save(priceEntity);
                    } else {
                        priceService.update(priceEntity);
                    }
                }
            }
        }
        //更新的话删除没有的
        if (actGoodsVo.getGoods().getId() != null) {
            //删除没有的
            List<Long> ids = actGoodsVo.getGoods().getPrices().stream().map(PriceEntity::getId).collect(Collectors.toList());
            priceService.deleteNotIn(ids, actGoodsVo.getGoods().getId());
        }
        //上架审核成功送优惠券
        rewardCoupon(actGoodsVo.getGoods());

        return actGoodsVo.getGoods();
    }

    // 变更售卖类型就需清空奖励  主要代理有利和清货模式
    private void saleTypeInit(Integer saleType, SaleTypeInfoEntity saleTypeInfoEntity) {
        if (saleType == MallGoodsSaleTypeEnum.AGENT.getIndex() || saleType == MallGoodsSaleTypeEnum.DAY_SEL.getIndex() || saleType == MallGoodsSaleTypeEnum.CLEAR.getIndex()) {
//            if (saleType != MallGoodsSaleTypeEnum.CLEAR.getIndex()) {
//                saleTypeInfoEntity.setClearReward(null);
//                saleTypeInfoEntity.setMaxClear(BigDecimal.ZERO);
//            }
//            saleTypeInfoEntity.setVoucherReward(null);
//            saleTypeInfoEntity.setCashReward(null);
//            saleTypeInfoEntity.setCouponReward(null);
//            saleTypeInfoEntity.setMaxCoupon(BigDecimal.ZERO);
//            saleTypeInfoEntity.setMaxVoucher(BigDecimal.ZERO);
        }
    }

    private void saveOrUpdate(ActGoodsVo actGoodsVo) {
        if (actGoodsVo.getAct().getNumber() != null) {
            Calendar cal = Calendar.getInstance();
            actGoodsVo.getAct().setStart(cal.getTime());  //设置开始时间
            cal.add(Calendar.YEAR, 1);
            actGoodsVo.getAct().setEnd(cal.getTime()); //设置结束时间
            actGoodsVo.getAct().setStatus(MallActStatusEnum.OPEN.getIndex());
            actGoodsVo.getAct().setStock(actGoodsVo.getGoods().getStock()); //设置库存
            actGoodsVo.getAct().setName(actGoodsVo.getGoods().getName()); //设置活动名
            actGoodsVo.getAct().setGoodsId(actGoodsVo.getGoods().getId());
            if (actGoodsVo.getAct().getId() != null) {
                mallActDao.update(actGoodsVo.getAct());
            } else {
                mallActDao.save(actGoodsVo.getAct());
            }
        }
    }

    @Autowired
    AccountRecordDao accountRecordDao;
    @Autowired
    AccountService accountService;

    /* que
     ** 上架审核成功送优惠券
     */
    private void rewardCoupon(MallGoodsEntity mallGoodsEntity) {
        Long userId = mallGoodsEntity.getUserId();
        //查记录 是否存在已经赠送过优惠券
        if (userId != null && !userId.equals(Const.ADMIN_ID)) {
            AccountRecordEntity entity = accountRecordDao.findByToUserIdAndTypeAndInfo(mallGoodsEntity.getUserId(), AccountTypeEnum.COUPON.getIndex(), "产品id:" + mallGoodsEntity.getId());
            //不存在
            if (entity == null) {
                //赠送优惠券
                if (mallGoodsEntity.getShelf() == MallGoodsShelfEnum.ON.getIndex()) {
                    accountService.transfer(Const.ADMIN_ID, userId, AccountTypeEnum.COUPON.getIndex(), new BigDecimal(20), "店家上架产品审核通过赠送优惠券,产品id:" + mallGoodsEntity.getId());
                }
            }
        }
    }

    @Override
    public MallGoodsEntity getWithSku(Long goodsId) {
        MallGoodsEntity mallGoodsEntity = mallGoodsDao.get(goodsId);
        List<MallSkuThemeEntity> themeEntities = mallSkuThemeDao.queryListByGoodsId(mallGoodsEntity.getId());
        for (MallSkuThemeEntity skuThemeEntity : themeEntities) {
            List<MallSkuItemEntity> itemEntities = mallSkuItemDao.queryListBySkuId(skuThemeEntity.getId());
            skuThemeEntity.setItems(itemEntities);
        }
        mallGoodsEntity.setSkuThemes(themeEntities);
        List<MallSkuEntity> mallSkuEntities = mallSkuDao.queryListByGoodsId(goodsId);
        mallGoodsEntity.setMallSkus(mallSkuEntities);
        return mallGoodsEntity;
    }


    @Override
    public List<MallGoodsEntity> topList(int limit, int page) {
        PageHelper.startPage(page, limit);
        HashMap param = new HashMap();
        //只查上架了的
        param.put("shelf", MallGoodsShelfEnum.ON.getIndex());
        param.put("order", "sort");
        List<MallGoodsEntity> mallGoodsEntities = mallGoodsDao.queryList(param);
        return apiFilter(mallGoodsEntities);
    }

    @Override
    public MallGoodsEntity getDetail(Long goodsId) {
        MallGoodsEntity mallGoodsEntity = getWithSku(goodsId);
        return apiFilter(mallGoodsEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MallGoodsEntity updateStock(StockRecordEntity stockRecordEntity) {
        String skuName = stockRecordEntity.getSkuName();
        //产品规格存在 更新sku相关信息 同步更新总数
        if (skuName != null && !skuName.equals("")) {
            if (stockRecordEntity.getQuantity() > 0) {
                mallGoodsDao.increaseStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
                mallGoodsDao.increaseSkuStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getSkuName(), stockRecordEntity.getQuantity());
            } else {
                mallGoodsDao.decreaseStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
                mallGoodsDao.decreaseSkuStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getSkuName(), stockRecordEntity.getQuantity());
            }
        } else { //产品规格不存在  更新产品库存 跟公司账户库存
            if (stockRecordEntity.getQuantity() > 0) {
                mallGoodsDao.increaseStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
                //增加公司账户库存
                mallStoreService.increase(Const.ADMIN_ID, stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
            } else {
                mallGoodsDao.decreaseStock(stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
                //减少公司账户库存
                mallStoreService.decrease(Const.ADMIN_ID, stockRecordEntity.getGoodsId(), stockRecordEntity.getQuantity());
            }
        }
        //保存记录
        stockRecordDao.save(stockRecordEntity);
        return mallGoodsDao.get(stockRecordEntity.getGoodsId());
    }

    @Override
    public List<MallGoodsEntity> findNoGoodId(Long id) {
        return mallGoodsDao.findNoGoodId(id);
    }

    @Autowired
    private GoodsQualificationDao goodsQualificationDao;

    @Autowired
    MallTypeDao mallTypeDao;
    @Autowired
    SaleTypeInfoDao saleTypeInfoDao;


    public void saveFromGoods(ActGoodsVo actGoodsVo, Long userId) {
        //保存产品分类资质
        if (actGoodsVo.getGoodsQualificationEntity() != null) {
            ///只有不是公司的才添加资质信息
            if (userId != null) {
                actGoodsVo.getGoodsQualificationEntity().setUserId(userId);
            }
            actGoodsVo.getGoodsQualificationEntity().setGoodsId(actGoodsVo.getGoods().getId());
            goodsQualificationDao.save(actGoodsVo.getGoodsQualificationEntity());
        }
        saveGoodsIdAndTypeId(actGoodsVo.getTypes(), actGoodsVo.getGoods().getId()); //保存分类
    }

    public void updateFromGoods(ActGoodsVo actGoodsVo, Long userId) {
        if (actGoodsVo.getSaleTypeInfoEntity().getTransfer() == null) {
            if (actGoodsVo.getGoods().getSaleType() == MallGoodsSaleTypeEnum.AGENT.getIndex()||actGoodsVo.getGoods().getSaleType() == MallGoodsSaleTypeEnum.DAY_SEL.getIndex()) {
                actGoodsVo.getSaleTypeInfoEntity().setTransfer(MallActRewardTypeEnum.yes.getIndex());  //是否转货
            } else {
                actGoodsVo.getSaleTypeInfoEntity().setTransfer(MallActRewardTypeEnum.no.getIndex());  //是否转货
            }
        }
        saleTypeInfoDao.update(actGoodsVo.getSaleTypeInfoEntity());
        addType(actGoodsVo.getGoods(), actGoodsVo.getTypes(), userId);
        //修改产品资质  不存在则添加
        if (actGoodsVo.getGoodsQualificationEntity().getId() == null) {
            //如果是公司账号 不做保存操作
            if (actGoodsVo.getGoodsQualificationEntity() != null) {
                actGoodsVo.getGoodsQualificationEntity().setGoodsId(actGoodsVo.getGoods().getId());
                if (userId != null) {
                    actGoodsVo.getGoodsQualificationEntity().setUserId(userId);
                }
                goodsQualificationDao.save(actGoodsVo.getGoodsQualificationEntity());
            }
        } else {
            goodsQualificationDao.update(actGoodsVo.getGoodsQualificationEntity());
        }
    }

    /**
     * quequnlong
     * 添加产品时添加对应的活动和分类
     *
     * @param
     */
    private void addType(MallGoodsEntity goods, List<Long> types, Long userId) {
//        MallActEntity actEntity = actGoodsVo.getAct();
//        actEntity.setGoodsId(actGoodsVo.getGoods().getId());
        List typeId = mallTypeDao.findByGoodsId(goods.getId());
        Boolean flag = true;
        if (typeId.containsAll(types)) {
            if (typeId.size() == types.size()) {
                flag = false;
            }
        }
        //先删分类在添加
        if (types == null || types.size() == 0) {
            //只有公司如果分类为空才删
            if (userId == null) {
                mallTypeDao.delByGoodsId(goods.getId());
            }
        }
        if (types != null && types.size() > 0 && flag) {
            //先删分类在添加
            mallTypeDao.delByGoodsId(goods.getId());
            saveGoodsIdAndTypeId(types, goods.getId());
        }
    }

    //设置活动一些默认值
    private void initAct(ActGoodsVo actGoodsVo, MallGoodsEntity goods) {
        actGoodsVo.getSaleTypeInfoEntity().setGoodsId(goods.getId());
        if (actGoodsVo.getSaleTypeInfoEntity().getPointType() == null) {  //积分奖励是否立即到账
            actGoodsVo.getSaleTypeInfoEntity().setPointType(MallActRewardTypeEnum.no.getIndex());
        }
        if (actGoodsVo.getSaleTypeInfoEntity().getCouponType() == null) {  //优惠券奖励是否立即到账
            actGoodsVo.getSaleTypeInfoEntity().setCouponType(MallActRewardTypeEnum.no.getIndex());
        }
        if (actGoodsVo.getSaleTypeInfoEntity().getVoucherType() == null) {//换购券奖励是否立即到账
            actGoodsVo.getSaleTypeInfoEntity().setVoucherType(MallActRewardTypeEnum.no.getIndex());
        }
        if (actGoodsVo.getSaleTypeInfoEntity().getCashType() == null) {//代金券奖励是否立即到账
            actGoodsVo.getSaleTypeInfoEntity().setCashType(MallActRewardTypeEnum.no.getIndex());
        }
        if (actGoodsVo.getSaleTypeInfoEntity().getManagerType() == null) {//管理费奖励是否立即到账
            actGoodsVo.getSaleTypeInfoEntity().setManagerType(MallActRewardTypeEnum.no.getIndex());
        }
        if (actGoodsVo.getSaleTypeInfoEntity().getAreaType() == null) {//区域奖励是否立即到账
            actGoodsVo.getSaleTypeInfoEntity().setAreaType(MallActRewardTypeEnum.no.getIndex());
        }
        if (actGoodsVo.getSaleTypeInfoEntity().getClearType() == null) {//赠送清货券是否立即到账
            actGoodsVo.getSaleTypeInfoEntity().setClearType(MallActRewardTypeEnum.no.getIndex());
        }
    }

    /**
     * 添加产品对应的分类
     *
     * @param types
     * @param goodsId
     */
    private void saveGoodsIdAndTypeId(List<Long> types, Long goodsId) {
        if (types != null && types.size() > 0) {
            for (Long type : types) {
                MallTypeEntity mallTypeEntity = mallTypeDao.get(type);
                //如果是一级分类 不添加
                if (mallTypeEntity.getPid() == null) {
                    continue;
                }
                mallTypeDao.saveGoodsIdAndTypeId(goodsId, type);
            }
        }
    }

    @Override
    public void delByUserId(Long userId) {
        mallGoodsDao.delByUserId(userId);
    }

    /**
     * 删除产品时删除对应的活动
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delByGoodsId(Long[] ids) {
        mallTypeDao.delByGoodsIdBatch(ids);
        mallActDao.deleteGoodsIdBatch(ids);
        saleTypeInfoDao.deleteGoodsIdBatch(ids);
        goodsQualificationDao.deleteByGoodsIdBatch(ids);
        mallGoodsDao.deleteBatch(ids);
    }

    @Override //quequnlong
    public List<MallGoodsEntity> findGoods() {
        return mallGoodsDao.findGoods(MallGoodsShelfEnum.ON.getIndex());
    }


    @Override
    public List<Map> mapBySaleType(Long userId, Long saleTypeId) {
        Map<Long, List<MallGoodsEntity>> map = new HashMap();
        List<MallGoodsEntity> list = mallGoodsDao.findBySaleTypeId(saleTypeId);
        //筛选不可见级别的
        LevelEntity levelEntity = levelDao.findByUserId(userId);
        list = filterByLevel(userId, list);
        list.forEach(l -> {
            List<MallGoodsEntity> tem;
            Long key = l.getType();
            if (key == null) {
                return;
            }
            if (map.containsKey(key)) {
                tem = map.get(key);
            } else {
                tem = new ArrayList<>();
            }
            tem.add(l);
            map.put(key, tem);
        });
        List<Map> result = new ArrayList<>();
        //找出分类
        map.keySet().forEach(key -> {
            Map tem = new HashMap();
            MallTypeEntity type = mallTypeDao.get(key);
            if (type == null) return;
            tem.put("name", type.getName());
            tem.put("img", type.getImg());
            tem.put("id", type.getId());
            tem.put("list", map.get(key));
            result.add(tem);
        });
        return result;
    }

    @Override   //根据标签id查询
    public List<MallGoodsEntity> findBySaleType(Map<String, Object> map, Long type) {
        List<MallGoodsEntity> list = new ArrayList<>();
        Integer saleType = (Integer) map.get("saleType"); //获取功能区id
        if (null != type && type != 0) { //判断是否是首页  为true则不是首页
            //获取一级分类的所有二级分类
            List<MallTypeEntity> mallTypeEntityList = mallTypeDao.findByParentId(type);
            if (mallTypeEntityList.size() > 0 && null != mallTypeEntityList) {
                for (MallTypeEntity typeEntity : mallTypeEntityList) {
                    //根据分类获取产品id
                    List<Long> goodsId = mallTypeDao.findByTypeId(typeEntity.getId());
                    if (null != goodsId && goodsId.size() > 0) {
                        for (Long goodId : goodsId) {
                            //获取产品
                            MallGoodsEntity goodsEntity = mallGoodsDao.get(goodId);
                            if (null != goodsEntity && goodsEntity.getSaleType() == saleType && goodsEntity.getShelf() == MallGoodsShelfEnum.ON.getIndex()) {
                                list.add(goodsEntity);
                            }
                        }
                    }
                }
            }
            return list;
        }

        return mallGoodsDao.findBySaleType(map);
    }

    @Override
    public List<PriceVo> priceTable(Long userId, Long goodId) {
        List<PriceVo> priceVos = new ArrayList<>();
        if (goodId == null) {
            return null;
        }
        //获取当前用户的级别
        LevelEntity levelEntity = levelDao.findByUserId(userId);
        UserEntity user = userDao.get(userId);
        PriceEntity price = priceService.findByLevelIdAndGoodsIdAndCode(levelEntity.getId(), goodId,user.getTCode());
        PriceVo priceVoEntity = new PriceVo();
        priceVoEntity.setPrice(price);
        priceVoEntity.setLevel(levelEntity);
        priceVos.add(priceVoEntity);
        //获取低于当前用户的级别
        List<LevelEntity> levelEntities = levelDao.findNextLv(levelEntity.getLv());

        //获取级别对应的价格
        if (levelEntities != null && levelEntities.size() > 0) {
            for (LevelEntity entity : levelEntities) {
                PriceEntity priceEntity = priceService.findByLevelIdAndGoodsIdAndCode(entity.getId(), goodId,user.getTCode());
                PriceVo priceVo = new PriceVo();
                priceVo.setPrice(priceEntity);
                priceVo.setLevel(entity);
                priceVos.add(priceVo);
            }
        }
        return priceVos;
    }
    

    /**
     * que
     * 获取用户上架的产品 针对店家
     *
     * @param userId
     * @return
     */
    @Override
    public List<MallGoodsEntity> findByUserId(Long userId, Integer shelf) {
        List<MallGoodsEntity> list = null;
        //获取公司的商品
        if (userId == null) {
            list = mallGoodsDao.findUserIdIsNull(shelf);
        } else {
            list = mallGoodsDao.findByUserId(userId, shelf);
        }
        return list;
    }

    @Override
    public List<MallGoodsEntity> findByTypeAndGoodsNameAndShelf(Integer type, String name, Integer shelf, Long userId, Integer saleType) {
        return mallGoodsDao.findByTypeAndGoodsNameAndShelf(type, name, shelf, userId, saleType);
    }


    @Override
    public List<MallGoodsEntity> filterByLevel(Long userId, List<MallGoodsEntity> mallGoodsEntities) {
        UserEntity user = userDao.get(userId);
        return mallGoodsEntities.stream().filter(mallGoodsEntity -> {
            MallActEntity mallActEntity = mallActDao.findByGoodsIdAndstatus(mallGoodsEntity.getId(), MallActStatusEnum.OPEN.getIndex());
            if (mallGoodsEntity.getDisplay() == null) {
                mallGoodsEntity.setDisplay(MallGoodsDisplayEnum.YES.getIndex());
            }
            //限制是否可见
            if (mallGoodsEntity.getDisplay() != null && mallGoodsEntity.getDisplay().equals(MallGoodsDisplayEnum.NO.getIndex())) {
                return false;
            }
            //填写了团队
            if (mallGoodsEntity.getTCode() != null && !mallGoodsEntity.getTCode().equals("") && !mallGoodsEntity.getTCode().contains(user.getTCode())) {
                return false;
            }
            UserEntity userEntity = userDao.get(userId);
            LevelEntity levelEntity = levelDao.get(userEntity.getLevelId());
            if (mallActEntity != null && mallActEntity.getOpen()) {
                // 限制了当前级别
                if (mallActEntity.getLevel() != null && !mallActEntity.getLevel().equals("") && mallActEntity.getLevel().contains(levelEntity.getName())) {
                    return false;
                }
            }

            //不可见
            if (mallGoodsEntity.getLevelName() != null && mallGoodsEntity.getLevelName().contains(levelEntity.getName())) {
                return false;
            }

            return true;
        }).collect(Collectors.toList());
    }


    @Override  //根据分类id查询产品
    public List<MallGoodsEntity> queryMallGoods(Map<String, Object> map) {
        Long typeId = (Long) map.get("typeId");
        List<MallGoodsEntity> mallGoodsEntities = mallTypeDao.findByTypeIdAndShelf(typeId, MallGoodsShelfEnum.ON.getIndex());
        //排序  quequnlong
        mallGoodsEntities.sort((o1, o2) -> {
            if (null != o1.getSort() && null != o2.getSort()) {
                if (o1.getSort() > o2.getSort()) {
                    return 1;
                }
            }
            return -1;
        });
        return mallGoodsEntities;
    }

    @Override  //根据产品名查询
    public List<MallGoodsEntity> searchName(String name) {
        return mallGoodsDao.searchName(name, MallGoodsShelfEnum.ON.getIndex());
    }


    /**
     * 获取所有每日优选产品
     *
     * @param shelf
     * @param dailySel
     * @param saleType
     * @return
     */
    @Override
    public List<MallGoodsEntity> findDailyList(Integer shelf, Integer dailySel, Integer dailySelRotation) {
        return mallGoodsDao.findDailyList(shelf, dailySel, dailySelRotation);
    }

    @Override
    public List<MallGoodsEntity> daily() {
        return mallGoodsDao.findByDaily(MallGoodsShelfEnum.ON.getIndex(),
                MallGoodsDailySelEnum.OPEN.getIndex());
    }

    @Override
    public List<MallGoodsEntity> findByHome(Integer saleType, Integer page, Integer limit) {
        PageHelper.startPage(page,limit).setOrderBy("sort");
        return mallGoodsDao.findByHome(saleType,MallGoodsShelfEnum.ON.getIndex());
    }
}


